package org.zjsru.product.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zjsru.product.mapper.ProductMapper;
import org.zjsru.product.pojo.Product;
import org.zjsru.product.service.ProductService;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 商品服务实现类
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${product.cache.expire-time:3600}")
    private Long cacheExpireTime;

    private static final String PRODUCT_CACHE_KEY = "product:";
    private static final String PRODUCT_LIST_CACHE_KEY = "product:list:";

    @Override
    public Product getProductById(Long id) {
        // 先从缓存获取
        // String cacheKey = PRODUCT_CACHE_KEY + id;
        // Product product = (Product) redisTemplate.opsForValue().get(cacheKey);
        // if (product != null) {
        //     log.info("从缓存获取商品信息，商品ID: {}", id);
        //     return product;
        // }

        // 缓存未命中，从数据库查询
        Product product = productMapper.selectById(id);
        // if (product != null) {
        //     // 放入缓存
        //     redisTemplate.opsForValue().set(cacheKey, product, cacheExpireTime, TimeUnit.SECONDS);
        //     log.info("商品信息已缓存，商品ID: {}", id);
        // }
        return product;
    }

    @Override
    public List<Product> getAllProducts() {
        // 先从缓存获取
        // String cacheKey = PRODUCT_LIST_CACHE_KEY + "all";
        // List<Product> products = (List<Product>) redisTemplate.opsForValue().get(cacheKey);
        // if (products != null) {
        //     log.info("从缓存获取商品列表");
        //     return products;
        // }

        // 缓存未命中，从数据库查询
        List<Product> products = productMapper.selectAll();
        // if (products != null && !products.isEmpty()) {
        //     // 放入缓存
        //     redisTemplate.opsForValue().set(cacheKey, products, cacheExpireTime, TimeUnit.SECONDS);
        //     log.info("商品列表已缓存");
        // }
        return products;
    }

    @Override
    public List<Product> getProductsByCategory(String category) {
        // 先从缓存获取
        // String cacheKey = PRODUCT_LIST_CACHE_KEY + "category:" + category;
        // List<Product> products = (List<Product>) redisTemplate.opsForValue().get(cacheKey);
        // if (products != null) {
        //     log.info("从缓存获取分类商品列表，分类: {}", category);
        //     return products;
        // }

        // 缓存未命中，从数据库查询
        List<Product> products = productMapper.selectByCategory(category);
        // if (products != null && !products.isEmpty()) {
        //     // 放入缓存
        //     redisTemplate.opsForValue().set(cacheKey, products, cacheExpireTime, TimeUnit.SECONDS);
        //     log.info("分类商品列表已缓存，分类: {}", category);
        // }
        return products;
    }

    @Override
    @Transactional
    public Product createProduct(Product product) {
        int result = productMapper.insert(product);
        if (result > 0) {
            // 清除相关缓存
            // clearProductCache();
            log.info("创建商品成功，商品ID: {}", product.getId());
            return product;
        }
        return null;
    }

    @Override
    @Transactional
    public Product updateProduct(Product product) {
        int result = productMapper.update(product);
        if (result > 0) {
            // 清除相关缓存
            // clearProductCache();
            // 更新单个商品缓存
            // String cacheKey = PRODUCT_CACHE_KEY + product.getId();
            // redisTemplate.opsForValue().set(cacheKey, product, cacheExpireTime, TimeUnit.SECONDS);
            log.info("更新商品成功，商品ID: {}", product.getId());
            return product;
        }
        return null;
    }

    @Override
    @Transactional
    public boolean deleteProduct(Long id) {
        int result = productMapper.deleteById(id);
        if (result > 0) {
            // 清除相关缓存
            // clearProductCache();
            // 删除单个商品缓存
            // String cacheKey = PRODUCT_CACHE_KEY + id;
            // redisTemplate.delete(cacheKey);
            log.info("删除商品成功，商品ID: {}", id);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean decreaseStock(Long productId, Integer quantity) {
        int result = productMapper.decreaseStock(productId, quantity);
        if (result > 0) {
            // 清除相关缓存
            // clearProductCache();
            log.info("扣减库存成功，商品ID: {}, 数量: {}", productId, quantity);
            return true;
        }
        log.warn("扣减库存失败，商品ID: {}, 数量: {}", productId, quantity);
        return false;
    }

    @Override
    @Transactional
    public boolean increaseStock(Long productId, Integer quantity) {
        int result = productMapper.increaseStock(productId, quantity);
        if (result > 0) {
            // 清除相关缓存
            // clearProductCache();
            log.info("恢复库存成功，商品ID: {}, 数量: {}", productId, quantity);
            return true;
        }
        log.warn("恢复库存失败，商品ID: {}, 数量: {}", productId, quantity);
        return false;
    }

    @Override
    public List<Product> searchProductsByName(String name) {
        return productMapper.selectByNameLike("%" + name + "%");
    }

    /**
     * 清除商品相关缓存
     */
    private void clearProductCache() {
        // 清除商品列表缓存
        // redisTemplate.delete(PRODUCT_LIST_CACHE_KEY + "all");
        // 这里可以添加更多缓存清理逻辑
        log.info("商品缓存已清除");
    }
} 